package com.example.administrator.wallet.custom;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;

import com.alibaba.fastjson.JSONArray;
import com.example.administrator.wallet.constant.Api;

import org.greenrobot.eventbus.EventBus;
import org.java_websocket.handshake.ServerHandshake;

public class MyWebSocketService extends Service implements WebSocketStateChangeListener {

    private MyWebSocketClient client;
    private static final long HEART_BEAT_RATE = 15 * 1000;
    private Handler mHandler = new Handler();
    private long sendTime = 0L;
    String token = "TxpUMccv-7oYfMyfpce0SCxBxLYqWdxJ_1533713782";

    public MyWebSocketService() {

    }

    public class ServiceBinder extends Binder{
        public MyWebSocketService getService(){
            return MyWebSocketService.this;
        }
    }

    private ServiceBinder binder = new ServiceBinder();

    @Override
    public IBinder onBind(Intent intent) {

        return binder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        client = MyWebSocketClient.initWebsocket(Api.WEBSOCKETURL,this);
        mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE);//开启心跳检测
    }

    @Override
    public void onOpen(ServerHandshake handshakedata) {
        client.join(token);
    }

    @Override
    public void onMessage(String mes) {
        EventBus.getDefault().post(new MessageEvent(mes));
    }

    @Override
    public void onClose(int code, String reason, boolean remote) {

    }

    @Override
    public void onError(Exception ex) {

    }

    public int sendMessage(String method, JSONArray jsonArray){
        int id = client.sendMessage(method,jsonArray);
        return id;
    }

    public int join(){
        int id = client.join(token);
        return id;
    }

    private Runnable heartBeatRunnable = new Runnable() {
        @Override
        public void run() {
            if (System.currentTimeMillis() - sendTime >= HEART_BEAT_RATE) {
                if (client.isClosed()){
                    mHandler.removeCallbacks(heartBeatRunnable);
                    client = null;
                    client = MyWebSocketClient.initWebsocket(Api.WEBSOCKETURL,MyWebSocketService.this);
                } else {
                    client.join(token);
                }

                sendTime = System.currentTimeMillis();
            }

            mHandler.postDelayed(this,HEART_BEAT_RATE);//每隔一定的时间，对长连接进行一次心跳检测
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        client = null;
        mHandler.removeCallbacks(heartBeatRunnable);
    }
}
